package io;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ws
 * Date: 2023-07-06
 * Time: 16:01
 */
public class IODemo9 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入一个扫描的的根目录：");
        File rootDir = new File(scanner.next());
        if (!rootDir.isDirectory()) {
            System.out.println("输入有误");
            return;
        }
        System.out.println("请输入要查询的词：");
        String word = scanner.next();
        scanDir(rootDir, word);
    }

    private static void scanDir(File rootDir, String word) {
        File[] files = rootDir.listFiles();
        if (files == null) {
            return;
        }
        for (File f: files) {
            if (f.isFile()) {//普通文件
                //打开文件，进行比较
                String content = readFile(f);
                if (content.contains(word)) {
                    System.out.println(f.getAbsolutePath() + "包含查找关键字");
                }
            } else if (f.isDirectory()) {//目录文件
                //进行递归
                scanDir(f, word);
            } else {//其他文件，直接跳过
                continue;
            }
        }
    }

    private static String readFile(File f) {
        //读取文件的整个内容，返回
        //匹配字符，采用字符流
        StringBuilder sb  = new StringBuilder();
        try (Reader reader = new FileReader(f)) {
            //一次读一个，在拼装
            while (true) {
                int c = reader.read();
                if (c == -1) {
                    break;
                }
                sb.append((char) c);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
}
